package dao;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import util.Conversion;
import dto.InterviewDTO;
import dto.QuestionDTO;
import dto.TemplateCategoryDTO;
import dto.TemplateDTO;
import dto.TestQuestionDTO;
import entities.Candidate;
import entities.Employee;
import entities.Interview;
import entities.Question;
import entities.Room;
import entities.Template;
import entities.TestQuestion;


/**
 * Session Bean implementation class InterviewDAO
 */
@Stateless
public class InterviewDAO implements InterviewDAORemote {

 	@PersistenceContext
   	EntityManager em;
 	@EJB
	TemplateCategoryDAORemote tcDAO;
 	@EJB
 	CandidateDAORemote cdao;
 	@EJB
 	EmployeeDAORemote edao;
 	@EJB
 	RoomDAORemote rdao;
	@EJB
 	QuestionDAORemote qDAO;
	@EJB
	TestQuestionDAORemote tqDAO;
   	Conversion conv  = new Conversion();
   	
   	
    public InterviewDAO() {
        // TODO Auto-generated constructor stub
    }
   
    
        public String getDateByInterviewId (int id) {
        	SimpleDateFormat sdf=new SimpleDateFormat ("dd-MM-yyyy");
        	TypedQuery<Interview> query = em.createQuery("Select i from Interview i where i.id= :id",
    				Interview.class);
    		query.setParameter("id", id);
    		List<Interview> results = query.getResultList();
    		return sdf.format(results.get(0).getDate());
        }

   
        public String getAddressByInterviewId (int id) {
        	TypedQuery<Room> query = em.createQuery("Select r from Interview i join i.room r where i.id= :id",
    				Room.class);
    		query.setParameter("id", id);
    		List<Room> results = query.getResultList();

    		return results.get(0).getAddress();
        }


        public Time getStartTimeByInterviewId (int id) {
        	TypedQuery<Interview> query = em.createQuery("Select i from Interview i where i.id= :id",
    				Interview.class);
    		query.setParameter("id", id);
    		List<Interview> results = query.getResultList();

    		return results.get(0).getStartTime();


        }
        
        @Override
        public void setAcceptedTrueForInterview(){
        	Interview i=em.find(Interview.class,1);
        	i.setAccepted((byte) 1);
        	em.merge(i);
        }
        
        @Override
        public void setAcceptedFalseForInterview() {
        	Interview i=em.find(Interview.class,1);
        	i.setAccepted((byte) 0);
        	em.merge(i);
        }
        
        //returns the InterviewDTO of an interview with identity id
        public InterviewDTO getInterview(int id){
        	InterviewDTO interview= new InterviewDTO();
        	Interview i=em.find(Interview.class,id);
        	try {
				interview= conv.fromInterviewToInterviewDTO(i);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("Getting interviewDTO with id: "+interview.getId());
        	return interview;
        }
        
        public int addInterview(InterviewDTO idto, int idEmployee, int idCandidate, int idTemplate, int idRoom) throws Exception
        {
        	int id=0;
		try {
			id = idto.getId();
		} catch (Exception ex){}
			conv= new Conversion();
        	Interview i=conv.fromInterviewDTOToInterviewWithoutForeign(idto);
        	try{
           	if (id!=0) i.setId(id);} catch (Exception ex){}
        	System.out.println(i.getComment());
        	TypedQuery<Candidate> cquery = em.createQuery(
					"SELECT c FROM Candidate c WHERE c.id = :idEmp"
							, Candidate.class);
			cquery.setParameter("idEmp", idCandidate);
			List<Candidate> cresult=cquery.getResultList();
			if(cresult.size()>0)
				i.setCandidate(cresult.get(0));
	    	TypedQuery<Employee> equery = em.createQuery(
					"SELECT e FROM Employee e WHERE e.id = :idEmp"
							, Employee.class);
			equery.setParameter("idEmp", idEmployee);
			List<Employee> eresult=equery.getResultList();
			if(eresult.size()>0)
				i.setEmployee(eresult.get(0));
	    	TypedQuery<Template> tquery = em.createQuery(
					"SELECT t FROM Template t WHERE t.id = :idTemp"
							, Template.class);
			tquery.setParameter("idTemp", idTemplate);
			List<Template> tresult=tquery.getResultList();
			if(tresult.size()>0)
				i.setTemplate(tresult.get(0));
	    	TypedQuery<Room> rquery = em.createQuery(
					"SELECT r FROM Room r WHERE r.id = :idRoom"
							, Room.class);
			rquery.setParameter("idRoom", idRoom);
			List<Room> rresult=rquery.getResultList();
			if(rresult.size()>0)
				i.setRoom(rresult.get(0));
			
//			rdao.getBusyPlacesInterval(idto.getStartTime(), i.getRoom().getId(), idto.getDate());
			
        	if ((em.find(Interview.class, i.getId()) != null)) {
				em.merge(i);
			System.out.println("Edited interview with "+i.getId());
			} else {
				em.persist(i);
				TypedQuery<Interview> resquery = em.createQuery(
						"SELECT i FROM Interview i ORDER BY i.id DESC"
								, Interview.class);
				Interview inter = resquery.getResultList().get(0);
				return inter.getId();
			}	
        	return 0;
        }

    
       
        //gets the comment from the selected interview
        public String getComment(int id){
        	String comment="";
        	TypedQuery<Interview> query = em.createQuery("Select i from Interview i where i.id= :id",
    				Interview.class);
    		query.setParameter("id", id);
    		Interview result = query.getSingleResult();
    		comment= result.getComment();
    		return comment;
        }
        
        //sets the comment field of the Interview table
        public void setComment (int id,String comment) {
        	TypedQuery<Interview> query = em.createQuery("Select i from Interview i where i.id= :id",
    				Interview.class);
    		query.setParameter("id", id);
    		Interview result = query.getSingleResult();
    		result.setComment(comment);
    		em.merge(result);


        }


        @Override
    	public int getInterviewDuration(int id) {
    		// TODO Auto-generated method stub
    		TypedQuery <Template> query = em.createQuery("select t from Interview i join i.template t where i.id= :id", Template.class);
    		query.setParameter("id", id);
    		return query.getResultList().get(0).getDuration();

    	}
        
        public void addInterview(InterviewDTO iDTO){
        	//iDTO.g
        }
		
        //deletes an interview
        public void deleteInterview(int id){
        	System.out.println("deleting int with id "+id);
        	TypedQuery<Interview> query = em.createQuery("Select i from Interview i where i.id= :id",
    				Interview.class);
    		query.setParameter("id", id);
    		List<Interview> interv= new ArrayList<Interview>();
    		Interview result = query.getSingleResult();
    		try{
    		Room room= result.getRoom();
    		interv=room.getInterviews();
    		interv.remove(result);
    		room.setInterviews(interv);
    		
    		em.merge(room);
    		Template template= result.getTemplate();
    		interv= template.getInterviews();
    		interv.remove(result);
    		template.setInterviews(interv);
    		
    		em.merge(template);
    		Candidate candidate= result.getCandidate();
    		interv=candidate.getInterviews();
    		interv.remove(result);
    		candidate.setInterviews(interv);
    		
    		em.merge(candidate);
    		Employee employee= result.getEmployee();
    		interv=employee.getInterviews();
    		interv.remove(result);
    		employee.setInterviews(interv);
    		em.merge(employee);
    		}catch (Exception ex){}
    		em.remove(result);
    		 
        }
        
        /**
         * Generates questions for the interview with id=iDTO
         * */
    	public void generateQuestions(InterviewDTO iDTO) {
    		TemplateDTO template = iDTO.getTemplate();
    		
    		
    		TypedQuery<Interview> queryInterview = em.createQuery("Select i from Interview i where i.id= :iid",
    				Interview.class);
    		queryInterview.setParameter("iid", iDTO.getId());
    		Interview interview = queryInterview.getSingleResult();
    		
    		TypedQuery<Question> queryQuestion = em.createQuery("Select q from Question q where q.id= :qid",
    				Question.class);
    		

    		for (TemplateCategoryDTO t : tcDAO.getTemplateCategoryListByTemplate(template)) {
    			List<QuestionDTO> allQuestions = qDAO.getAllValidQuestionsByCategory(t.getCategory());
    			Collections.shuffle(allQuestions);
    			for (int i = 0; i < t.getNumberOfQuestions() && i < allQuestions.size() ; i++) {
//    				questionIds.add(allQuestions.get(i).getId());
    				
    	    		queryQuestion.setParameter("qid", allQuestions.get(i).getId());
    	    		Question question = queryQuestion.getSingleResult();
    	    		TestQuestion testQuestion = new TestQuestion();
    	    		testQuestion.setInterview(interview);
    	    		testQuestion.setCandidateAnswer(-1);
    				testQuestion.setQuestion(question);
    				em.persist(testQuestion);
    				interview.getTestQuestions().add(testQuestion);
    				try {
						List<TestQuestionDTO> l=tqDAO.getInterviewQuestions(iDTO.getId());
						for(TestQuestionDTO x:l){
							conv.fromTestQuestionDTOToTestQuestion(x);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
    			}
    		}
    		
    		
    	}

        @Override
        public void addInterviewForAllocating(InterviewDTO iDTO){
        	Interview i=new Interview();
        	Employee e=em.find(Employee.class, iDTO.getEmployee().getId());
        	Candidate c=em.find(Candidate.class,iDTO.getCandidate().getId());
        	i.setEmployee(e);
        	i.setCandidate(c);
        	em.persist(i);
        	e.getInterviews().add(i);
        	c.getInterviews().add(i);
        }
        
        
        
        
        
        
        
}

